package com.bwie.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bwie.mapper.GoodsMapper;
import com.bwie.pojo.Goods;
import com.bwie.service.GoodsService;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    private GoodsMapper goodsMapper;


    RestHighLevelClient client=new RestHighLevelClient(
            RestClient.builder(new HttpHost("47.102.97.160",9200,"http"))
    );

    private static final String INDEX_NAME="goods";

    @Override
    public void updateGoodsStatus(Goods goods) {
        goodsMapper.updateGoodsStatus(goods);
        Goods goods1 = findById(goods.getId());
        goods1.setGoodsStatus(1);
        updateGoods(goods1);
    }

    @Override
    public void downGoodsStatus(Goods goods) {
        goodsMapper.downGoodsStatus(goods);
        Goods goods1 = findById(goods.getId());
        goods1.setGoodsStatus(2);
        updateGoods(goods1);
    }

    @Override
    public Goods findById(Integer id) {
        return goodsMapper.findById(id);
    }

    @Override
    public void update(Goods goods) {
        goodsMapper.update(goods);
        updateGoods(goods);
    }

    private void updateGoods(Goods goods) {
        IndexRequest indexRequest = new IndexRequest(INDEX_NAME);
        indexRequest.id(goods.getId() + "");
        indexRequest.source(JSONObject.toJSONString(goods), XContentType.JSON);
        try {
            client.index(indexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
